{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jlE_jisTkXY4"
      },
      "source": [
        "**Copyright 2021 The TensorFlow Authors.**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "mEE8NFIMSGO-"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SyiSRgdtSGPC"
      },
      "source": [
        "# Sparsity preserving clustering Keras example"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/model_optimization/guide/combine/sparse_clustering_example\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/combine/sparse_clustering_example.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/combine/sparse_clustering_example.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/model-optimization/tensorflow_model_optimization/g3doc/guide/combine/sparse_clustering_example.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dKnJyAaASGPD"
      },
      "source": [
        "## Overview\n",
        "\n",
        "This is an end to end example showing the usage of the **sparsity preserving clustering** API, part of the TensorFlow Model Optimization Toolkit's collaborative optimization pipeline.\n",
        "\n",
        "### Other pages\n",
        "\n",
        "For an introduction to the pipeline and other available techniques, see the [collaborative optimization overview page](https://www.tensorflow.org/model_optimization/guide/combine/collaborative_optimization).\n",
        "\n",
        "### Contents\n",
        "\n",
        "In the tutorial, you will:\n",
        "\n",
        "1. Train a `tf.keras` model for the MNIST dataset from scratch.\n",
        "2. Fine-tune the model with sparsity and see the accuracy and observe that the model was successfully pruned.\n",
        "3. Apply weight clustering to the pruned model and observe the loss of sparsity.\n",
        "4. Apply sparsity preserving clustering on the pruned model and observe that the sparsity applied earlier has been preserved.\n",
        "5. Generate a TFLite model and check that the accuracy has been preserved in the pruned clustered model.\n",
        "6. Compare the sizes of the different models to observe the compression benefits of applying sparsity followed by the collaborative optimization technique of sparsity preserving clustering."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RgcQznnZSGPE"
      },
      "source": [
        "## Setup\n",
        "\n",
        "You can run this Jupyter Notebook in your local [virtualenv](https://www.tensorflow.org/install/pip?lang=python3#2.-create-a-virtual-environment-recommended) or [colab](https://colab.sandbox.google.com/). For details of setting up dependencies, please refer to the [installation guide](https://www.tensorflow.org/model_optimization/guide/install). "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3asgXMqnSGPE"
      },
      "outputs": [],
      "source": [
        "! pip install -q tensorflow-model-optimization"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gL6JiLXkSGPI"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "\n",
        "import numpy as np\n",
        "import tempfile\n",
        "import zipfile\n",
        "import os"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dKzOfl5FSGPL"
      },
      "source": [
        "## Train a tf.keras model for MNIST to be pruned and clustered"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "w7Fd6jZ7SGPL"
      },
      "outputs": [],
      "source": [
        "# Load MNIST dataset\n",
        "mnist = tf.keras.datasets.mnist\n",
        "(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n",
        "\n",
        "# Normalize the input image so that each pixel value is between 0 to 1.\n",
        "train_images = train_images / 255.0\n",
        "test_images  = test_images / 255.0\n",
        "\n",
        "model = tf.keras.Sequential([\n",
        "  tf.keras.layers.InputLayer(input_shape=(28, 28)),\n",
        "  tf.keras.layers.Reshape(target_shape=(28, 28, 1)),\n",
        "  tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3),\n",
        "                         activation=tf.nn.relu),\n",
        "  tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),\n",
        "  tf.keras.layers.Flatten(),\n",
        "  tf.keras.layers.Dense(10)\n",
        "])\n",
        "\n",
        "# Train the digit classification model\n",
        "model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "\n",
        "model.fit(\n",
        "    train_images,\n",
        "    train_labels,\n",
        "    validation_split=0.1,\n",
        "    epochs=10\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rBOQ8MeESGPO"
      },
      "source": [
        "### Evaluate the baseline model and save it for later usage"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HYulekocSGPP"
      },
      "outputs": [],
      "source": [
        "_, baseline_model_accuracy = model.evaluate(\n",
        "    test_images, test_labels, verbose=0)\n",
        "\n",
        "print('Baseline test accuracy:', baseline_model_accuracy)\n",
        "\n",
        "_, keras_file = tempfile.mkstemp('.h5')\n",
        "print('Saving model to: ', keras_file)\n",
        "tf.keras.models.save_model(model, keras_file, include_optimizer=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HPoCr4OFkXZE"
      },
      "source": [
        "## Prune and fine-tune the model to 50% sparsity"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4mucwWWikXZE"
      },
      "source": [
        "Apply the `prune_low_magnitude()` API to prune the whole pre-trained model to achieve the model that is to be clustered in the next step. For how best to use the API to achieve the best compression rate while maintaining your target accuracy, refer to the [pruning comprehensive guide](https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OGfTFitgkXZF"
      },
      "source": [
        "### Define the model and apply the sparsity API\n",
        "\n",
        "Note that the pre-trained model is used."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mqsN5tP-kXZF"
      },
      "outputs": [],
      "source": [
        "import tensorflow_model_optimization as tfmot\n",
        "\n",
        "prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude\n",
        "\n",
        "pruning_params = {\n",
        "      'pruning_schedule': tfmot.sparsity.keras.ConstantSparsity(0.5, begin_step=0, frequency=100)\n",
        "  }\n",
        "\n",
        "callbacks = [\n",
        "  tfmot.sparsity.keras.UpdatePruningStep()\n",
        "]\n",
        "\n",
        "pruned_model = prune_low_magnitude(model, **pruning_params)\n",
        "\n",
        "# Use smaller learning rate for fine-tuning\n",
        "opt = tf.keras.optimizers.Adam(learning_rate=1e-5)\n",
        "\n",
        "pruned_model.compile(\n",
        "  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "  optimizer=opt,\n",
        "  metrics=['accuracy'])\n",
        "\n",
        "pruned_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mh6SzEP9kXZF"
      },
      "source": [
        "### Fine-tune the model, check sparsity, and evaluate the accuracy against baseline\n",
        "\n",
        "Fine-tune the model with pruning for 3 epochs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2aBxR8uEkXZG"
      },
      "outputs": [],
      "source": [
        "# Fine-tune model\n",
        "pruned_model.fit(\n",
        "  train_images,\n",
        "  train_labels,\n",
        "  epochs=3,\n",
        "  validation_split=0.1,\n",
        "  callbacks=callbacks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GALLq2ZlkXZG"
      },
      "source": [
        "Define helper functions to calculate and print the sparsity of the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XL-zWoU4kXZG"
      },
      "outputs": [],
      "source": [
        "def print_model_weights_sparsity(model):\n",
        "\n",
        "    for layer in model.layers:\n",
        "        if isinstance(layer, tf.keras.layers.Wrapper):\n",
        "            weights = layer.trainable_weights\n",
        "        else:\n",
        "            weights = layer.weights\n",
        "        for weight in weights:\n",
        "            if \"kernel\" not in weight.name or \"centroid\" in weight.name:\n",
        "                continue\n",
        "            weight_size = weight.numpy().size\n",
        "            zero_num = np.count_nonzero(weight == 0)\n",
        "            print(\n",
        "                f\"{weight.name}: {zero_num/weight_size:.2%} sparsity \",\n",
        "                f\"({zero_num}/{weight_size})\",\n",
        "            )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TZRAJVqWkXZG"
      },
      "source": [
        "Check that the model kernels was correctly pruned. We need to strip the pruning wrapper first. We also create a deep copy of the model to be used in the next step."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_8_p--1NkXZG"
      },
      "outputs": [],
      "source": [
        "stripped_pruned_model = tfmot.sparsity.keras.strip_pruning(pruned_model)\n",
        "\n",
        "print_model_weights_sparsity(stripped_pruned_model)\n",
        "\n",
        "stripped_pruned_model_copy = tf.keras.models.clone_model(stripped_pruned_model)\n",
        "stripped_pruned_model_copy.set_weights(stripped_pruned_model.get_weights())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cWPgcnjKSGPR"
      },
      "source": [
        "## Apply clustering and sparsity preserving clustering and check its effect on model sparsity in both cases"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y2wKK7w9SGPS"
      },
      "source": [
        "Next, we apply both clustering and sparsity preserving clustering on the pruned model and observe that the latter preserves sparsity on your pruned model. Note that we stripped pruning wrappers from the pruned model with `tfmot.sparsity.keras.strip_pruning` before applying the clustering API."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RetnGeQnkXZH"
      },
      "outputs": [],
      "source": [
        "# Clustering\n",
        "cluster_weights = tfmot.clustering.keras.cluster_weights\n",
        "CentroidInitialization = tfmot.clustering.keras.CentroidInitialization\n",
        "\n",
        "clustering_params = {\n",
        "  'number_of_clusters': 8,\n",
        "  'cluster_centroids_init': CentroidInitialization.KMEANS_PLUS_PLUS\n",
        "}\n",
        "\n",
        "clustered_model = cluster_weights(stripped_pruned_model, **clustering_params)\n",
        "\n",
        "clustered_model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "\n",
        "print('Train clustering model:')\n",
        "clustered_model.fit(train_images, train_labels,epochs=3, validation_split=0.1)\n",
        "\n",
        "\n",
        "stripped_pruned_model.save(\"stripped_pruned_model_clustered.h5\")\n",
        "\n",
        "# Sparsity preserving clustering\n",
        "from tensorflow_model_optimization.python.core.clustering.keras.experimental import (\n",
        "    cluster,\n",
        ")\n",
        "\n",
        "cluster_weights = cluster.cluster_weights\n",
        "\n",
        "clustering_params = {\n",
        "  'number_of_clusters': 8,\n",
        "  'cluster_centroids_init': CentroidInitialization.KMEANS_PLUS_PLUS,\n",
        "  'preserve_sparsity': True\n",
        "}\n",
        "\n",
        "sparsity_clustered_model = cluster_weights(stripped_pruned_model_copy, **clustering_params)\n",
        "\n",
        "sparsity_clustered_model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "\n",
        "print('Train sparsity preserving clustering model:')\n",
        "sparsity_clustered_model.fit(train_images, train_labels,epochs=3, validation_split=0.1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "A_PNNJoQkXZH"
      },
      "source": [
        "Check sparsity for both models."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iHN3NW8OkXZI"
      },
      "outputs": [],
      "source": [
        "print(\"Clustered Model sparsity:\\n\")\n",
        "print_model_weights_sparsity(clustered_model)\n",
        "print(\"\\nSparsity preserved clustered Model sparsity:\\n\")\n",
        "print_model_weights_sparsity(sparsity_clustered_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ea40z522SGPT"
      },
      "source": [
        "## Create 1.6x smaller models from clustering\n",
        "\n",
        "Define helper function to get zipped model file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "obozrEwrkXZI"
      },
      "outputs": [],
      "source": [
        "def get_gzipped_model_size(file):\n",
        "  # It returns the size of the gzipped model in kilobytes.\n",
        "\n",
        "  _, zipped_file = tempfile.mkstemp('.zip')\n",
        "  with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:\n",
        "    f.write(file)\n",
        "\n",
        "  return os.path.getsize(zipped_file)/1000"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RTjq8zjnkXZJ"
      },
      "outputs": [],
      "source": [
        "# Clustered model\n",
        "clustered_model_file = 'clustered_model.h5'\n",
        "\n",
        "# Save the model.\n",
        "clustered_model.save(clustered_model_file)\n",
        "    \n",
        "#Sparsity Preserve Clustered model\n",
        "sparsity_clustered_model_file = 'sparsity_clustered_model.h5'\n",
        "\n",
        "# Save the model.\n",
        "sparsity_clustered_model.save(sparsity_clustered_model_file)\n",
        "    \n",
        "print(\"Clustered Model size: \", get_gzipped_model_size(clustered_model_file), ' KB')\n",
        "print(\"Sparsity preserved clustered Model size: \", get_gzipped_model_size(sparsity_clustered_model_file), ' KB')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5bNfCJrEkXZJ"
      },
      "source": [
        "## Create a TFLite model from combining sparsity preserving weight clustering and post-training quantization\n",
        "\n",
        "Strip clustering wrappers and convert to TFLite."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "i4dI7XSakXZJ"
      },
      "outputs": [],
      "source": [
        "stripped_sparsity_clustered_model = tfmot.clustering.keras.strip_clustering(sparsity_clustered_model)\n",
        "\n",
        "converter = tf.lite.TFLiteConverter.from_keras_model(stripped_sparsity_clustered_model)\n",
        "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n",
        "sparsity_clustered_quant_model = converter.convert()\n",
        "\n",
        "_, pruned_and_clustered_tflite_file = tempfile.mkstemp('.tflite')\n",
        "\n",
        "with open(pruned_and_clustered_tflite_file, 'wb') as f:\n",
        "  f.write(sparsity_clustered_quant_model)\n",
        "\n",
        "print(\"Sparsity preserved clustered Model size: \", get_gzipped_model_size(sparsity_clustered_model_file), ' KB')\n",
        "print(\"Sparsity preserved clustered and quantized TFLite model size:\",\n",
        "       get_gzipped_model_size(pruned_and_clustered_tflite_file), ' KB')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "konsqRkokXZK"
      },
      "source": [
        "## See the persistence of accuracy from TF to TFLite"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "c1HTl0x0kXZK"
      },
      "outputs": [],
      "source": [
        "def eval_model(interpreter):\n",
        "  input_index = interpreter.get_input_details()[0][\"index\"]\n",
        "  output_index = interpreter.get_output_details()[0][\"index\"]\n",
        "\n",
        "  # Run predictions on every image in the \"test\" dataset.\n",
        "  prediction_digits = []\n",
        "  for i, test_image in enumerate(test_images):\n",
        "    if i % 1000 == 0:\n",
        "      print(f\"Evaluated on {i} results so far.\")\n",
        "    # Pre-processing: add batch dimension and convert to float32 to match with\n",
        "    # the model's input data format.\n",
        "    test_image = np.expand_dims(test_image, axis=0).astype(np.float32)\n",
        "    interpreter.set_tensor(input_index, test_image)\n",
        "\n",
        "    # Run inference.\n",
        "    interpreter.invoke()\n",
        "\n",
        "    # Post-processing: remove batch dimension and find the digit with highest\n",
        "    # probability.\n",
        "    output = interpreter.tensor(output_index)\n",
        "    digit = np.argmax(output()[0])\n",
        "    prediction_digits.append(digit)\n",
        "\n",
        "  print('\\n')\n",
        "  # Compare prediction results with ground truth labels to calculate accuracy.\n",
        "  prediction_digits = np.array(prediction_digits)\n",
        "  accuracy = (prediction_digits == test_labels).mean()\n",
        "  return accuracy"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_I1gdnbCkXZK"
      },
      "source": [
        "You evaluate the model, which has been pruned, clustered and quantized, and then see that the accuracy from TensorFlow persists in the TFLite backend."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lbumQ_-0kXZL"
      },
      "outputs": [],
      "source": [
        "# Keras model evaluation\n",
        "stripped_sparsity_clustered_model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "_, sparsity_clustered_keras_accuracy = stripped_sparsity_clustered_model.evaluate(\n",
        "    test_images, test_labels, verbose=0)\n",
        "\n",
        "# TFLite model evaluation\n",
        "interpreter = tf.lite.Interpreter(pruned_and_clustered_tflite_file)\n",
        "interpreter.allocate_tensors()\n",
        "\n",
        "sparsity_clustered_tflite_accuracy = eval_model(interpreter)\n",
        "\n",
        "print('Pruned, clustered and quantized Keras model accuracy:', sparsity_clustered_keras_accuracy)\n",
        "print('Pruned, clustered and quantized TFLite model accuracy:', sparsity_clustered_tflite_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VQFbw88ykXZL"
      },
      "source": [
        "## Conclusion"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7JhbpowqSGP1"
      },
      "source": [
        "In this tutorial, you learned how to create a model, prune it using the `prune_low_magnitude()` API, and apply sparsity preserving clustering to preserve sparsity while clustering the weights. The sparsity preserving clustered model was compared to a clustered one to show that sparsity is preserved in the former and lost in the latter. Next, the pruned clustered model was converted to TFLite to show the compression benefits of chaining the pruning and sparsity preserving clustering model optimization techniques and, finally, the TFLite model was evaluated to ensure that the accuracy persists in the TFLite backend."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "sparse_clustering_example.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
